#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zconf.h>
#include <pthread.h>
#include <fcntl.h>
#include "sysinfo.h"
#include "procps.h"
#include "getsysinfo.h"

#define BUFFSIZE 65536

extern unsigned int rd_num;
extern unsigned long long rd_bytes;
extern double fs_ra;
extern double mem_ra;
extern double cpu_ra;

char buff[BUFFSIZE];

void sys_info_write_to_log() {
    int fd_log = -1;
    int fd_data = -1;
    if ((fd_log = open("data/sys_info.log", O_CREAT | O_RDWR | O_APPEND, 0777)) < 0) {
        perror("open file err!\n");
        exit(EXIT_FAILURE);
    }
    if ((fd_data = open("data/sysinfo_data.csv", O_CREAT | O_RDWR | O_APPEND, 0777)) < 0) {
        perror("open file err!\n");
        exit(EXIT_FAILURE);
    }

    time_t timep;
    time(&timep);//获取时间
    sprintf(buff,"time:%s\n",ctime(&timep));
    write(fd_log, buff, strlen(buff));

    sprintf(buff,"%ld ",timep);
    write(fd_data, buff, strlen(buff));
    sprintf(buff,"%u %llu %.2lf%% %.2lf%% %.2lf%%\n\n",rd_num,rd_bytes,mem_ra,fs_ra,cpu_ra);
    write(fd_data, buff, strlen(buff));


    sprintf(buff,"┌────────disk stat────────────┐\n");
    write(fd_log, buff, strlen(buff));
    sprintf(buff,"│  number of read and write:        %u      │\n", rd_num);
    write(fd_log, buff, strlen(buff));
    sprintf(buff,"│  number of read and write bytes:  %llu     │\n", rd_bytes);
    write(fd_log, buff, strlen(buff));
    sprintf(buff,"└─────────disk stat───────────┘\n");
    write(fd_log, buff, strlen(buff));

    sprintf(buff,"\n");
    write(fd_log, buff, strlen(buff));

    sprintf(buff,"┌────────memory_stat───────────┐\n");
    write(fd_log, buff, strlen(buff));
    sprintf(buff,"│   memory usage rate = %.2lf%%                    │\n", mem_ra);
    write(fd_log, buff, strlen(buff));
    sprintf(buff,"└─────────memory_stat──────────┘\n");
    write(fd_log, buff, strlen(buff));

    sprintf(buff,"\n");
    write(fd_log, buff, strlen(buff));

    sprintf(buff,"┌────────memory stat───────────┐\n");
    write(fd_log, buff, strlen(buff));
    sprintf(buff,"│  fs usage rate = %.2lf%%                          │\n", fs_ra);
    write(fd_log, buff, strlen(buff));
    sprintf(buff,"└─────────memory stat──────────┘\n");
    write(fd_log, buff, strlen(buff));

    sprintf(buff,"\n");
    write(fd_log, buff, strlen(buff));

    sprintf(buff,"┌─────────cpu stat────────────┐\n");
    write(fd_log, buff, strlen(buff));
    sprintf(buff,"│  cpu usage rate = %.2lf%%                          │\n", cpu_ra);
    write(fd_log, buff, strlen(buff));
    sprintf(buff,"└─────────cpu stat────────────┘\n");
    write(fd_log, buff, strlen(buff));

    sprintf(buff, "\n\n");
    write(fd_log, buff, strlen(buff));
    close(fd_log);

}

